<template>
    <div class="page-container">
        <template v-if="!showDetail">
            <div class="top-container">
                <div class="left-section">
                    <el-checkbox
                        v-model="isAllSelected"
                        @change="handleSelectAll"
                        class="select-all-checkbox"
                    >
                        全选
                    </el-checkbox>
                </div>
                <div class="right-section">
                    <el-select v-model="videoType" placeholder="视频类型" class="video-type custom-select"
                        @change="handleTypeChange">
                        <el-option label="一键成片" value="type1" />
                        <el-option label="数字人" value="type2" />
                        <el-option label="数字人Pro" value="type3" />
                        <el-option label="图生视频" value="type4" />
                    </el-select>
                    <el-input
                        v-model="searchText"
                        placeholder="请输入搜索内容"
                        class="search-input custom-input"
                        :prefix-icon="Search"
                        @keyup.enter="handleSearch"
                    />
                    <el-divider direction="vertical" />
                    <el-button type="primary" @click="sendSelectMaterialConfirm">
                      <el-icon style="margin-right: 5px;">
                        <Check />
                      </el-icon>
                      确定
                    </el-button>
                </div>
            </div>
            <div class="content-wrapper">
                <div class="content-list">
                    <el-row :gutter="24">
                        <el-col :span="12" v-for="item in pageData" :key="item.id">
                            <div class="card" @click="handleCardClick(item.id)">
                                <div class="card-header">
                                    <el-checkbox v-model="item.checked" @click.stop @change="handleCheckboxChange(item, $event)" />
                                    <span class="card-title">{{ item.title }}</span>
                                    <span class="card-meta-info">{{ item.classify_name }} {{ item.addtime }}</span>
                                </div>
                                <div class="card-body">
                                    <video v-if="item.video_url_video" :src="item.video_url_video" class="card-img" disabled></video>
                                    <img v-else :src="item.video_url_image" class="card-img" />
                                    <div class="card-info">
                                        <div class="card-count">
                                            <span class="count">{{ item.ossnum }}</span> 个
                                            <div class="desc">成品总量</div>
                                        </div>
                                        <div class="card-meta">
                                            <div>
                                                <span class="count">{{ item.fb_num }}</span> 个
                                                <div class="desc">已发布数量</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div class="pagination-bar">
                    <el-pagination
                        background
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        :page-size="pageSize"
                        :current-page="currentPage"
                        @size-change="handleSizeChange"
                        @current-change="handlePageChange"
                        :page-sizes="[10,20,50,100]"
                    />
                </div>
            </div>
        </template>
        <ProductVideoDetail v-else :video-id="selectedVideoId" :type="videoType" :select-video-son-item="selectVideoSonItem" @back="handleBack" @update:select-video-son-item="handleUpdateSelection" />
        <el-dialog v-model="showDeleteDialog" title="确认删除" width="300px" :close-on-click-modal="false">
            <span>确定要删除吗？</span>
            <template #footer>
                <el-button @click="showDeleteDialog = false">取消</el-button>
                <el-button type="danger" @click="handleConfirmDelete">确定</el-button>
            </template>
        </el-dialog>
        <MyDialog v-model="showMobileDownloadDialog" width="420px"  @confirm="handleConfirm" title="请使用手机扫码下载">
            <div style="text-align:center; padding: 16px 0;">
                <img src="/videoDownLoadPhone.png" alt="二维码" style="width:180px; height:180px;" />
            </div>
        </MyDialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import axiosUtil from '../../axios-util/axios-util'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import ProductVideoDetail from './ProductVideoDetailNew.vue'
import {useRouter} from "vue-router";
import MyDialog from '../common/MyDialog.vue'
import { el } from 'element-plus/es/locales.mjs'
import EmptyImg from '../../assets/images/empty.png'
import utils from '../../utils/utils'

//主题控制light  dark
const theme = utils.getTheme();
const website_bg_url = ref('')
const router = useRouter()

const videoType = ref('type1')
const searchText = ref('')

const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const pageData = ref([])
const loading = ref(false)

const showDetail = ref(false)
const selectedVideoId = ref<number | null>(null)
const showDeleteDialog = ref(false)
const showMobileDownloadDialog = ref(false)
const isAllSelected = ref(false)
const selectVideoSonItem = ref([])

const emit = defineEmits(['confirm']);

const itovTypeMap = {
    'iv_default':"默认风格",
    'iv_wudongrenxiang':"舞动人像",
    'iv_yuechangdongyan':"悦唱动演",
    'iv_lingdongbobao':"灵动播报",
    'iv_biaoqingbao':"表情包",
    'iv_duotucankao':"多图参考",
    'iv_kouxingtihuan':"口型替换",
    'iv_chonghui':"重绘",
}

const handleConfirm = () => {
    showMobileDownloadDialog.value = false
}

const fetchList = async () => {
  loading.value = true
  console.log(videoType.value)
  let params: Record<string, any> = {
    id: '',
    limit: pageSize.value,
    offset: currentPage.value,
    status: '',
    title: searchText.value,
    type: 1,
 }
 let url = 'api/storeintopieces/send_list'
  if(videoType.value === 'type2'){
    params.protype = ''
    url = 'api/digitalpeople/list'
  }
  if(videoType.value === 'type3'){
    params.protype = 2
    url = 'api/digitalpeople/list'
  }
  if(videoType.value === 'type4'){
    params.protype = ''
    url = 'api/aliyun_tongyi/wan_xiang/query_itov_list'
  }
  if(videoType.value === 'type5'){
    params.protype = ''
    url = 'api/aliyun_tongyi/wan_xiang/query_ttov_list'
  }
  const response = await axiosUtil.post(url, params)
  loading.value = false
  if (response.data.code === 1 && response.data.data.rows) {
    pageData.value = response.data.data.rows
    // 新添加的图生视频字段需要映射转换
    if(videoType.value === 'type4') {
        transItov(response.data.data.rows)
    }
    // 新添加的文生视频字段需要映射转换
    if(videoType.value === 'type5') {
        transTtov(response.data.data.rows)
    }
    // 初始化选中状态
    pageData.value.forEach(item => {
        item.checked = false
    })
    total.value = response.data.data.total || 0
  }
}

function transItov(data: any[]){
  data.forEach(item => {
    item.classify_name = itovTypeMap[item.type] || '其他';
    item.addtime = item.create_time;
    if(item.base_image_url) {
        item.video_url_image = item.base_image_url;
    } else {
        item.video_url_video = item.base_video_url;
    }
    item.ossnum = item.success_count;
    item.fb_num = item.fb_count;
  })
}
import wssp from '../../assets/images/wssp.jpg'
function transTtov(data: any[]){
  data.forEach(item => {
    item.classify_name = itovTypeMap[item.type] || '其他';
    item.addtime = item.create_time;
    // 采用默认的文生视频图片
    item.video_url_image = wssp;
    item.ossnum_s = item.success_count;
    item.fb_num = item.fb_count;
  })
}

onMounted(() => {
  document.body.classList.remove('login-page')
  initWebsiteBgUrl()
  fetchList()
})

//读取配置，获取网站背景图
const initWebsiteBgUrl = async () => {
  const response = await axiosUtil.post('api/pc/site/get_agent_config', {})
  if (response.data.code === 0 && response.data.data) {
    website_bg_url.value = import.meta.env.VITE_APP_SERVER + response.data.data.website_bg || ''
  }
}

const handleNewTask = () => {
  router.push('/batchVideoBg')
}

const handlePublish = () => {
  // 处理发布
}

const handleDelete = () => {
  showDeleteDialog.value = true
}

const handleDownload = () => {
  // 处理下载
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchList()
}
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchList()
}

// 搜索和筛选
const handleSearch = () => {
  currentPage.value = 1
  fetchList()
}
const handleTypeChange = () => {
  currentPage.value = 1
  fetchList()
}

const handleCardClick = async (id: number) => {
    // 清空所有选择
    selectVideoSonItem.value = []
    
    // 清空所有checkbox的选中状态
    pageData.value.forEach((item: any) => {
        item.checked = false
    })
    
    // 更新全选状态
    isAllSelected.value = false
    
    selectedVideoId.value = id
    showDetail.value = true
}

const handleBack = () => {
    showDetail.value = false
    selectedVideoId.value = null
}

const handleUpdateSelection = (newSelection: any[]) => {
    selectVideoSonItem.value = newSelection
}

// 确定删除的方法由你自己实现
const handleConfirmDelete = async() => {
  // 这里写你自己的删除逻辑
  showDeleteDialog.value = false
  const selectedItems = pageData.value.filter((item: any) => item.checked);
  const selectedIds = selectedItems.map((item: any) => item.id);
  const response = await axiosUtil.post('api/buiattach/storeintopieces_del', {
    ids: selectedIds
  })
  if (response.data.code === 1) {
    ElMessage.success('删除成功')
  }else{
    ElMessage.error('删除失败：'+response.data.msg)
  }
  fetchList()
}

const handleDownloadToPC = () => {
  // 这里写下载到电脑的逻辑
  console.log('下载到电脑')
}

const handleDownloadToMobile = () => {
  showMobileDownloadDialog.value = true
}

// 处理 checkbox 变化
const handleCheckboxChange = (item: any, checked: boolean) => {
  console.log('checkbox changed:', item.id, checked) // 添加调试日志

  if (checked) {
    // 选中时添加到数组
    const existingIndex = selectVideoSonItem.value.findIndex((selectedItem: any) => selectedItem.id === item.id)
    if (existingIndex === -1) {
      selectVideoSonItem.value.push(item)
      console.log('added to selection:', item.id) // 添加调试日志
    }
  } else {
    // 取消选中时从数组中删除
    const index = selectVideoSonItem.value.findIndex((selectedItem: any) => selectedItem.id === item.id)
    if (index !== -1) {
      selectVideoSonItem.value.splice(index, 1)
      console.log('removed from selection:', item.id) // 添加调试日志
    }
  }

  console.log('current selection:', selectVideoSonItem.value) // 添加调试日志

  // 更新全选状态
  const checkedCount = pageData.value.filter((item: any) => item.checked).length
  isAllSelected.value = checkedCount === pageData.value.length && pageData.value.length > 0
}

// 全选/取消全选
const handleSelectAll = (checked: boolean) => {
  console.log('select all changed:', checked) // 添加调试日志

  pageData.value.forEach((item: any) => {
    item.checked = checked
  })

  if (checked) {
    // 全选时，将所有项目添加到数组
    selectVideoSonItem.value = [...pageData.value]
    console.log('all items selected:', selectVideoSonItem.value.length) // 添加调试日志
  } else {
    // 取消全选时，清空数组
    selectVideoSonItem.value = []
    console.log('all items deselected') // 添加调试日志
  }
}

const getSelectMateriaAll = () => {
  console.log('getSelectMateriaAll called, current selection:', selectVideoSonItem.value) // 添加调试日志
  return selectVideoSonItem.value
}

const sendSelectMaterialConfirm = () => {
  emit('confirm');
}

defineExpose({
  getSelectMateriaAll
})
</script>

<style scoped>
.page-container {
    position: relative;
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    display: flex;
    flex-direction: column;
}

.top-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
    backdrop-filter: blur(10px);
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"');
    border-radius: 8px;
    box-shadow: 0 4px 6px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(0, 0, 0, 0.3)"');
    position: relative;
    overflow: hidden;
    margin: 10px 20px;
}

.left-section {
    display: flex;
    align-items: center;
    gap: 12px;
}

.right-section {
    display: flex;
    align-items: center;
    gap: 12px;
}

.select-all-checkbox {
    color: v-bind('theme === "light" ? "#000" : "#fff"');
}

.select-all-checkbox :deep(.el-checkbox__label) {
    color: v-bind('theme === "light" ? "#000" : "#fff"');
}

.select-all-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
    border-color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
}

.video-type {
    width: 120px;
}

.search-input {
    width: 200px;
}

/* 自定义按钮样式 */
.custom-button {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"') !important;
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
    color: #fff !important;
    transition: all 0.3s ease !important;
}

.custom-button:hover {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.15)" : "rgba(0, 0, 0, 0.4)"') !important;
    border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.5)"') !important;
}

/* 自定义下拉框样式 */
.custom-select :deep(.el-input__wrapper) {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"') !important;
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
    box-shadow: none !important;
}

.custom-select :deep(.el-input__inner) {
    color: #fff !important;
}

.custom-select :deep(.el-input__wrapper:hover) {
    border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.5)"') !important;
    box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
}

/* 自定义输入框样式 */
.custom-input :deep(.el-input__wrapper) {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"') !important;
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
    box-shadow: none !important;
}

.custom-input :deep(.el-input__inner) {
    color: #fff !important;
}

.custom-input :deep(.el-input__wrapper:hover) {
    border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.5)"') !important;
    box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
}

/* 下拉选项样式 */
:deep(.el-select-dropdown) {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.95)" : "rgba(0, 0, 0, 0.95)"') !important;
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.1)"') !important;
    backdrop-filter: blur(10px);
}

:deep(.el-select-dropdown__item) {
    color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255, 0.8)"') !important;
}

:deep(.el-select-dropdown__item.hover),
:deep(.el-select-dropdown__item:hover) {
    background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(255, 255, 255, 0.1)"') !important;
    color: v-bind('theme === "light" ? "#000" : "#fff"') !important;
}

:deep(.el-select-dropdown__item.selected) {
    background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.2)" : "rgba(255, 255, 255, 0.2)"') !important;
    color: v-bind('theme === "light" ? "#000" : "#fff"') !important;
}

.content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 0 20px 10px;
    min-height: 0;
    overflow: hidden;
}

.content-list {
    flex: 1;
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.1)"');
    border-radius: 12px;
    box-shadow: 0 0 20px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.08)" : "rgba(0, 0, 0, 0.2)"');
    padding: 24px;
    overflow-y: auto;
    margin-bottom: 10px;
}

/* 自定义滚动条样式 */
.content-list::-webkit-scrollbar {
    width: 6px;
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.3)"');
}

.content-list::-webkit-scrollbar-thumb {
    background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "linear-gradient(180deg, rgba(0, 255, 255, 0.2), rgba(0, 255, 255, 0.4), rgba(0, 255, 255, 0.2))"');
    border-radius: 3px;
    border: 1px solid v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "rgba(0, 255, 255, 0.3)"');
    box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.2)" : "rgba(0, 255, 255, 0.2)"');
}

.content-list::-webkit-scrollbar-thumb:hover {
    background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.4)" : "linear-gradient(180deg, rgba(0, 255, 255, 0.3), rgba(0, 255, 255, 0.5), rgba(0, 255, 255, 0.3))"');
    box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "rgba(0, 255, 255, 0.3)"');
}

.content-list::-webkit-scrollbar-track {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.2)"');
    border-radius: 3px;
    border: 1px solid v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(0, 255, 255, 0.1)"');
}

.card {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.1)"');
    border-radius: 10px;
    margin-bottom: 24px;
    padding: 18px;
    display: flex;
    flex-direction: column;
    box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.08)" : "rgba(0, 0, 0, 0.2)"');
    transition: all 0.3s ease;
    cursor: pointer;
}

.card:hover {
    box-shadow: 0 0 24px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.18)" : "rgba(0, 0, 0, 0.3)"');
    transform: translateY(-2px);
    border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.4)" : "rgba(255, 255, 255, 0.2)"');
}

.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    gap: 8px;
}

.card-title {
    font-weight: bold;
    color: v-bind('theme === "light" ? "#000" : "#fff"');
    font-size: 1.1em;
}

.card-meta-info {
    color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.6)" : "#b2ebf2"');
    font-size: 0.9em;
    margin-left: auto;
    font-weight: 600;
}

.card-body {
    display: flex;
    align-items: center;
}

.card-img {
    width: 100px;
    height: 70px;
    object-fit: cover;
    border-radius: 6px;
    margin-right: 18px;
    border: 1px solid v-bind('theme === "light" ? "rgba(0, 0, 0, 0.15)" : "rgba(0, 255, 255, 0.15)"');
}

.card-info {
    flex: 1;
    display: flex;
    justify-content: space-between;
}

.card-count, .card-meta {
    color: v-bind('theme === "light" ? "#000" : "#fff"');
    font-size: 1em;
}

.count {
    color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
    font-weight: bold;
    font-size: 1.2em;
}

.desc {
    font-size: 0.85em;
    color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.6)" : "#b2ebf2"');
}

.pagination-bar {
    padding: 10px 20px;
    display: flex;
    justify-content: flex-end;
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
    border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.1)"');
    border-radius: 12px;
    box-shadow: 0 0 20px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.08)" : "rgba(0, 0, 0, 0.2)"');
}

/* 分页器样式 */
:deep(.el-pagination) {
    --el-pagination-bg-color: transparent;
    --el-pagination-button-color: v-bind('theme === "light" ? "#000" : "#fff"');
    --el-pagination-button-disabled-color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "rgba(255, 255, 255, 0.3)"');
    --el-pagination-hover-color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
}

:deep(.el-pagination .el-pagination__total) {
    color: v-bind('theme === "light" ? "#000" : "#fff"');
}

:deep(.el-pagination .el-pagination__jump) {
    color: v-bind('theme === "light" ? "#000" : "#fff"');
}

:deep(.el-pagination .el-pager li) {
    background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
    color: v-bind('theme === "light" ? "#000" : "#fff"');
}

:deep(.el-pagination .el-pager li.active) {
    background: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
    color: v-bind('theme === "light" ? "#fff" : "#000"');
}

:deep(.el-pagination .el-pager li:hover) {
    color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
}

.popover-download-row {
  display: flex;
  flex-direction: row;
  gap: 12px;
  justify-content: center;
  align-items: center;
}
.download-btn {
  flex: 1 1 0;
  min-width: 100px;
}
</style>
